import { type Object3D, type Object3DJSON, ObjectLoader } from 'three';

import type { Editor } from '../Editor.ts';
import { type BaseCommandJsonType, Command } from './Command.ts';

type AddObjectCommandJsonType = BaseCommandJsonType & { object: Object3DJSON };

class AddObjectCommand extends Command {
  object: Object3D;

  constructor(editor: Editor, object: Object3D) {
    super(editor);

    this.type = 'AddObjectCommand';
    this.object = object;
    this.name = `command/AddObject: ${object.name}`;
  }

  execute() {
    this.editor.addObject(this.object);
    this.editor.select(this.object);
  }

  undo() {
    this.editor.removeObject(this.object);
    this.editor.deselect();
  }

  update(_command: Command): void {}

  toJSON(): AddObjectCommandJsonType {
    return {
      ...super.toJSON(),
      object: this.object.toJSON(),
    };
  }

  fromJSON(json: AddObjectCommandJsonType) {
    super.fromJSON(json);
    if (!this.editor.objects.has(json.object.object.uuid)) {
      const loader = new ObjectLoader();
      this.object = loader.parse(json.object);
    }
  }
}

export { AddObjectCommand };
